<?php


namespace app\common\model;

use app\model\AdminClass;
use app\model\AdminLeaveForm;
use app\model\AdminLeaveProcessFlow;
use app\model\AdminLeaveSetting;
use app\util\ReturnCode;
use app\util\Strs;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;

class LeaveFromCommon
{
    // 生成请假审批流
    public static function leaveFromAdd($staff, $form_type, $reason, $start_time, $end_time) {
        // 查规则
        $leaveSetting = AdminLeaveSetting::where('school_id', $staff->school_id)
            ->where('is_delete', 0)
            ->where('setting_state', AdminLeaveSetting::STATE_ENABLE)->find();
        if (!$leaveSetting) {
            throw new \Exception('未设置请假规则，请联系管理员');
        }
        // 生成请假单
        $leave_form_id = AdminLeaveForm::insertGetId([
            "form_id" => Strs::randString(5, 2).Strs::randString(5, 1),
            "school_id" => $staff->school_id,
            "staff_id" => $staff->id,
            "form_type" => $form_type,
            "create_time" => time(),
            "start_time" => strtotime($start_time.' 00:00:00'),
            "end_time" => strtotime($end_time.' 23:23:59'),
            "reason" => $reason,
            "state" => AdminLeaveForm::STATE_PROCESSING
        ]);
        /** 生成审批流 */
        $order_no = 1;
        // 生成一条自己的申请记录
        AdminLeaveProcessFlow::create([
            "leave_form_id" => $leave_form_id,
            "school_id" => $staff->school_id,
            "staff_id" => $staff->id, // 审批人是自己
            "action" => AdminLeaveProcessFlow::ACTION_APPLY,
            "result" => AdminLeaveProcessFlow::RESULT_APPROVED,
            "reason" => '',
            "audit_time" => time(),
            "order_no" => $order_no++,
            "state" => AdminLeaveProcessFlow::STATE_COMPLETE,
            "is_last" => 0
        ]);
        // 生成班主任审批单
        if($leaveSetting->teacher_audit == 1){
            if(!$staff->class_id){
                throw new \Exception('您未分配班级信息，请联系管理员');
            }
            $class = AdminClass::where('id', $staff->class_id)->find();
            if(!$class){
                throw new \Exception('您未分配班级信息，请联系管理员');
            }
            AdminLeaveProcessFlow::create([
                "leave_form_id" => $leave_form_id,
                "school_id" => $staff->school_id,
                "staff_id" => $class->staff_id, // 审批人是班主任
                "action" => AdminLeaveProcessFlow::ACTION_AUDIT,
                "result" => '',
                "reason" => '',
                "order_no" => $order_no++,
                "state" => AdminLeaveProcessFlow::STATE_PROCESS,
                "is_last" => 0
            ]);
        }
        // 生成负责人的审批单
        $staff_ids = explode(',',$leaveSetting->staff_ids);
        $staff_ids_count = count($staff_ids);
        for($i = 0; $i < $staff_ids_count; $i++) {
            AdminLeaveProcessFlow::create([
                "leave_form_id" => $leave_form_id,
                "school_id" => $staff->school_id,
                "staff_id" => $staff_ids[$i], // 审批人
                "action" => AdminLeaveProcessFlow::ACTION_AUDIT,
                "result" => '',
                "reason" => '',
                "order_no" => $order_no,
                // 没有班主任审批时这里第一条状态为进行中
                "state" => ($order_no == 2) ? AdminLeaveProcessFlow::STATE_PROCESS : AdminLeaveProcessFlow::STATE_READY,
                "is_last" => ($i == ($staff_ids_count - 1))
            ]);
            $order_no++;
        }
    }

    // 请假审批
    public static function leaveFromAudit($staff, $leave_flow_id, $result, $reason) {
        // 查请假单
        $adminLeaveForm = AdminLeaveForm::where('id', $leave_flow_id)
            ->where('state', AdminLeaveForm::STATE_PROCESSING)->find();
        if (!$adminLeaveForm) {
            throw new \Exception('找不到请假单，暂时无法审批');
        }
        // 查审批中节点
        $adminLeaveProcessFlow = AdminLeaveProcessFlow::where('leave_form_id', $adminLeaveForm->id)
            ->where('state', AdminLeaveProcessFlow::STATE_PROCESS)->find();
        if (!$adminLeaveProcessFlow) {
            throw new \Exception('请假单结束，无法审批');
        }
        if($staff && $staff->id != $adminLeaveProcessFlow->staff_id){
            throw new \Exception('正在处理中，还未到您审批');
        }
        //1.无论审批结果是同意还是驳回，当前任务状态变更为complete
        $adminLeaveProcessFlow->state=AdminLeaveProcessFlow::STATE_COMPLETE;
        $adminLeaveProcessFlow->result=$result;
        $adminLeaveProcessFlow->reason=$reason;
        $adminLeaveProcessFlow->audit_time=time();
        $adminLeaveProcessFlow->save();
        //2.如果当前任务是最后一个节点，代表流程结束，更新leave_form表中的请假单状态为对应的approved或者refused
        if($adminLeaveProcessFlow->is_last == 1){
            $adminLeaveForm->state=$result;
            $adminLeaveForm->save();
            return;
        }
        //3.如果当前任务不是最后一个节点，如果审批通过，那么下一个节点的状态从ready改为process
        if($result == AdminLeaveProcessFlow::RESULT_APPROVED){
            $adminLeaveProcessFlow2 = AdminLeaveProcessFlow::where('leave_form_id', $adminLeaveProcessFlow->leave_form_id)
                ->where('order_no', ($adminLeaveProcessFlow->order_no+1))->find();
            if (!$adminLeaveProcessFlow2) {
                throw new \Exception('请假单处理异常，无法找到下一节点');
            }
            $adminLeaveProcessFlow2->state=AdminLeaveProcessFlow::STATE_PROCESS;
            $adminLeaveProcessFlow2->save();
        }
        //4.如果当前任务不是最后一个节点，如果审批驳回，则后续所有任务的状态变为cancel，同时更新leave_form表中的请假单状态为refused
        if($result == AdminLeaveProcessFlow::RESULT_REFUSED){
            $where = [
                ['leave_form_id', '=', $adminLeaveProcessFlow->leave_form_id],
                ['order_no', '>', $adminLeaveProcessFlow->order_no]
            ];
            AdminLeaveProcessFlow::update(['state' => AdminLeaveProcessFlow::STATE_CANCEL], $where);
            $adminLeaveForm->state=AdminLeaveForm::STATE_REFUSED;
            $adminLeaveForm->save();
        }
    }
}